//
//  IdeaCalendarMonthView.m
//  planner
//
//  Created by 함동균 on 2014. 3. 22..
//  Copyright (c) 2014년 idea. All rights reserved.
//

#import "IdeaCalendarMonthV.h"
#define HEADER_IMAGE_VIEW_HEIGHT        18.0
#define HEADER_CIRCLE_BACKGROUND_RADIUS 25.0

@interface IdeaCalendarMonthView ()
@property (nonatomic, strong) UIImageView* headerImageView;
@property (nonatomic, strong) NSMutableArray* weekdayLabels;
@property (nonatomic, strong) NSMutableArray* dayLabels;
@property (nonatomic, strong) NSMutableArray* dayBackgroundImageView;
@property (nonatomic, strong) NSMutableArray* xConstraints;
@property (nonatomic, strong) NSMutableArray* yConstraints;
@end

@implementation IdeaCalendarMonthView

#pragma mark Instanciator
- (void)setMonth:(CalendarMonth *)month
{
    _month = month;
    [self updateData];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self draw];
    }
    return self;
}

- (void)awakeFromNib
{
    [self draw];
}

#pragma mark Drawing and layingout UIs
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [self addLines];
}

- (void)draw
{
    [self setTabBarName];
    [self addSubviews];
    [self addLayoutConstraints];
    [self updateTheme];
}

- (void)setTabBarName
{
    self.tabBarName = TAB_BAR_CALENDAR;
}

- (void)addSubviews
{
    self.headerImageView = [[UIImageView alloc] init];
    [self addSubview:self.headerImageView];
    self.headerImageView.translatesAutoresizingMaskIntoConstraints = NO;
    
    
    self.weekdayLabels = [[NSMutableArray alloc] init];
    for (NSUInteger i = 0; i < 7; i++) {
        UILabel *weekdayLabel = [[UILabel alloc]init];
        [weekdayLabel setFont:[UIFont systemFontOfSize:11.0]];
        [self.weekdayLabels addObject:weekdayLabel];
        [self addSubview:[self.weekdayLabels objectAtIndex:i]];
        ((UILabel *)[self.weekdayLabels objectAtIndex:i]).translatesAutoresizingMaskIntoConstraints = NO;
    }
    
    self.dayBackgroundImageView = [[NSMutableArray alloc] init];
    for (NSUInteger i=0; i< 7 * 6; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        [self.dayBackgroundImageView addObject:imageView];
        [self addSubview:[self.dayBackgroundImageView objectAtIndex:i]];
        ((UIImageView *)[self.dayBackgroundImageView objectAtIndex:i]).translatesAutoresizingMaskIntoConstraints = NO;
    }

    self.dayLabels = [[NSMutableArray alloc] init];
    for (NSUInteger i = 0; i < 7 * 6; i++) {
        UILabel *dayLabel = [[UILabel alloc] init];
        [self.dayLabels addObject:dayLabel];
        [self addSubview:[self.dayLabels objectAtIndex:i]];
        ((UILabel *)[self.dayLabels objectAtIndex:i]).translatesAutoresizingMaskIntoConstraints = NO;
    }
}

- (void)addLines
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    if (context) {
        
        CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
        CGContextMoveToPoint(context, 0, 0);
        CGContextAddLineToPoint(context, self.bounds.size.width, 0);
        CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height);
        CGContextAddLineToPoint(context, 0, self.bounds.size.height);
        CGContextFillPath(context);
        
        CGContextSetLineWidth(context, 0.5f);
        
        for (CGFloat ytemp = 18 + [self getHeightSpan]; ytemp <= self.bounds.size.height; ytemp = ytemp + [self getHeightSpan]) {
            CGFloat y = ((int16_t)ytemp)*1.0f - 0.5f;
            
            CGContextSetStrokeColorWithColor(context, [[self getColorForProperty:DATE_LINE_COLOR] CGColor]);
            CGContextMoveToPoint(context, 0, y);
            CGContextAddLineToPoint(context, self.bounds.size.width, y);
            CGContextStrokePath(context);
        }
    }
}

- (void)addLayoutConstraints
{
    NSMutableArray *imageViewConstraints = [[NSMutableArray alloc] init];
    NSMutableArray *constraints = [[NSMutableArray alloc] init];
    self.xConstraints = [[NSMutableArray alloc] init];
    self.yConstraints = [[NSMutableArray alloc] init];
    
    // Image Header View Contrains
    [imageViewConstraints addObject:[NSLayoutConstraint constraintWithItem:self.headerImageView
                                                                 attribute:NSLayoutAttributeHeight
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:nil
                                                                 attribute:NSLayoutAttributeNotAnAttribute
                                                                multiplier:1.0f
                                                                  constant:HEADER_IMAGE_VIEW_HEIGHT]];
    [constraints addObject:[NSLayoutConstraint constraintWithItem:self.headerImageView
                                                        attribute:NSLayoutAttributeTop
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1.0f
                                                         constant:0.0f]];
    [constraints addObject:[NSLayoutConstraint constraintWithItem:self.headerImageView
                                                        attribute:NSLayoutAttributeLeft
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self
                                                        attribute:NSLayoutAttributeLeft
                                                       multiplier:1.0f
                                                         constant:0.0f]];
    [constraints addObject:[NSLayoutConstraint constraintWithItem:self.headerImageView
                                                        attribute:NSLayoutAttributeRight
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self
                                                        attribute:NSLayoutAttributeRight
                                                       multiplier:1.0f
                                                          constant:0.0f]];
    
    // Week Day Label Constraints
    [constraints addObject:[NSLayoutConstraint constraintWithItem:[self.weekdayLabels objectAtIndex:3]
                                                        attribute:NSLayoutAttributeCenterX
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.headerImageView
                                                        attribute:NSLayoutAttributeCenterX
                                                       multiplier:1.0f
                                                         constant:0.0f]];
    
    for (NSUInteger i = 0; i < 7; i++) {
        if ([self.weekdayLabels objectAtIndex:i]) {
            [constraints addObject:[NSLayoutConstraint constraintWithItem:[self.weekdayLabels objectAtIndex:i]
                                                                attribute:NSLayoutAttributeCenterY
                                                                relatedBy:NSLayoutRelationEqual
                                                                   toItem:self.headerImageView
                                                                attribute:NSLayoutAttributeCenterY
                                                               multiplier:1.0f
                                                                 constant:0.0f]];
            
            if (i > 0) {
                [self.xConstraints addObject:[NSLayoutConstraint constraintWithItem:[self.weekdayLabels objectAtIndex:i]
                                                                          attribute:NSLayoutAttributeCenterX
                                                                          relatedBy:NSLayoutRelationEqual
                                                                             toItem:[self.weekdayLabels objectAtIndex:i - 1]
                                                                          attribute:NSLayoutAttributeCenterX
                                                                         multiplier:1.0f
                                                                           constant:[self getWidthSpan]]];
            }
        }
    }
    
    [constraints addObject:[NSLayoutConstraint constraintWithItem:[self.dayLabels objectAtIndex:0]
                                                              attribute:NSLayoutAttributeTop
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:self.headerImageView
                                                              attribute:NSLayoutAttributeTop
                                                             multiplier:1.0f
                                                               constant:HEADER_IMAGE_VIEW_HEIGHT + 7.0f]];
    // Day Label Constraints
    for (NSUInteger row = 0; row < 6; row++) {
        if (row > 0) {
            [self.yConstraints addObject:[NSLayoutConstraint constraintWithItem:[self.dayLabels objectAtIndex:row*7]
                                                                      attribute:NSLayoutAttributeCenterY
                                                                      relatedBy:NSLayoutRelationEqual
                                                                         toItem:[self.dayLabels objectAtIndex:(row - 1)*7]
                                                                      attribute:NSLayoutAttributeCenterY
                                                                     multiplier:1.0f
                                                                       constant:[self getHeightSpan]]];
        }
        
        [constraints addObject:[NSLayoutConstraint constraintWithItem:[self.dayLabels objectAtIndex:row*7 + 3]
                                                            attribute:NSLayoutAttributeCenterX
                                                            relatedBy:NSLayoutRelationEqual
                                                               toItem: self.headerImageView
                                                            attribute:NSLayoutAttributeCenterX
                                                           multiplier:1.0f
                                                             constant:0.0f]];
        
        for (NSUInteger column = 0; column < 7; column++) {
            [constraints addObject:[NSLayoutConstraint constraintWithItem:[self.dayLabels objectAtIndex:row * 7 + column]
                                                                attribute:NSLayoutAttributeCenterX
                                                                relatedBy:NSLayoutRelationEqual
                                                                   toItem:[self.weekdayLabels objectAtIndex:column]
                                                                attribute:NSLayoutAttributeCenterX
                                                               multiplier:1.0f
                                                                 constant:0.0f]];
            if (column > 0) {
                [constraints addObject:[NSLayoutConstraint constraintWithItem:[self.dayLabels objectAtIndex:row * 7 + column]
                                                                    attribute:NSLayoutAttributeCenterY
                                                                    relatedBy:NSLayoutRelationEqual
                                                                       toItem:[self.dayLabels objectAtIndex:row * 7 + column - 1]
                                                                    attribute:NSLayoutAttributeCenterY
                                                                   multiplier:1.0f
                                                                     constant:0.0f]];
            }
            [constraints addObject:[NSLayoutConstraint constraintWithItem:[self.dayBackgroundImageView objectAtIndex:row * 7 + column]
                                                                attribute:NSLayoutAttributeCenterX
                                                                relatedBy:NSLayoutRelationEqual
                                                                   toItem:[self.dayLabels objectAtIndex:row * 7 + column]
                                                                attribute:NSLayoutAttributeCenterX
                                                               multiplier:1.0f
                                                                 constant:0.0f]];
            [constraints addObject:[NSLayoutConstraint constraintWithItem:[self.dayBackgroundImageView objectAtIndex:row * 7 + column]
                                                                attribute:NSLayoutAttributeCenterY
                                                                relatedBy:NSLayoutRelationEqual
                                                                   toItem:[self.dayLabels objectAtIndex:row * 7 + column]
                                                                attribute:NSLayoutAttributeCenterY
                                                               multiplier:1.0f
                                                                 constant:0.0f]];
        }
    }
    
    [self.headerImageView addConstraints:imageViewConstraints];
    [self addConstraints:constraints];
    [self addConstraints:self.xConstraints];
    [self addConstraints:self.yConstraints];
}

- (void)layoutSubviews
{
    if (self.xConstraints.count > 0) {
        for (NSLayoutConstraint *constraint in self.xConstraints) {
            constraint.constant = [self getWidthSpan];
        }
    }
    if (self.yConstraints.count > 0) {
        for (NSLayoutConstraint *constraint in self.yConstraints) {
            constraint.constant = [self getHeightSpan];
        }
    }
    [super layoutSubviews];
}

- (void)updateTheme
{
    [super updateTheme];
    [self addLines];
    [self drawHeaderImage];
    [self drawSelectedBackgroundImage];
    [self setWeekdayLabelsColor];
    [self setDayLabelsColor];
}

- (void)drawHeaderImage
{
    // Draw head Image
    CGSize imageSize = CGSizeMake(self.bounds.size.width, HEADER_IMAGE_VIEW_HEIGHT);
    UIGraphicsBeginImageContext(imageSize);
    
    // Draw image for header
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // Header Background
    CGContextSetFillColorWithColor(context, [[self getColorForProperty:HEADER_BACKGROUND_COLOR] CGColor]);
    CGContextFillRect(context, CGRectMake(0, 0, imageSize.width, imageSize.height));
    
    // Header Line
    CGContextSetStrokeColorWithColor(context, [[self getColorForProperty:HEADER_LINE_COLOR] CGColor]);CGContextMoveToPoint(context, 0, imageSize.height - 1.5);
    CGContextAddLineToPoint(context, imageSize.width, imageSize.height - 1.5);
    CGContextStrokePath(context);
    
    // Update Image
    self.headerImageView.image = UIGraphicsGetImageFromCurrentImageContext();
}

- (void)drawSelectedBackgroundImage
{
    for (int i = 0; i < 6 * 7; i++)
    {
        // Header Background
        if (self.month) {
            // Draw today Image
            CGRect imageRect = CGRectMake(0, 0, HEADER_CIRCLE_BACKGROUND_RADIUS, HEADER_CIRCLE_BACKGROUND_RADIUS);
            UIGraphicsBeginImageContext(imageRect.size);
            
            // Draw image for today circle
            CGContextRef context = UIGraphicsGetCurrentContext();
            CalendarDay *day = [self.month.days objectAtIndex:i];
            
            if (day.isToday) {
                CGContextSetFillColorWithColor(context, [[self getColorForProperty:DATE_TODAY_BACKGROUND_COLOR] CGColor]);
            } else if (day.isSelected){
                CGContextSetFillColorWithColor(context, [[self getColorForProperty:DATE_SELECTED_BACKGROUND_COLOR] CGColor]);
            } else {
                CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
            }
            
            CGContextFillEllipseInRect (context, imageRect);
            
            // Update Image
            ((UIImageView *)self.dayBackgroundImageView[i]).image = UIGraphicsGetImageFromCurrentImageContext();
        }
    }
}

- (void)setWeekdayLabelsColor
{
    for (NSUInteger i = 0; i < 7; i++) {
        UILabel *dayLabel = [self.weekdayLabels objectAtIndex:i];
        
        switch (i) {
            case 0:
                //Sunday
                [dayLabel setTextColor:[self getColorForProperty:HEADER_SUNDAY_TEXT_COLOR]];
                break;
            case 6:
                //Saturday
                [dayLabel setTextColor:[self getColorForProperty:HEADER_SATURDAY_TEXT_COLOR]];
                break;
            default:
                //Weekday
                [dayLabel setTextColor:[self getColorForProperty:HEADER_WEEKDAY_TEXT_COLOR]];
                break;
        }
    }
}

- (void)setDayLabelsColor
{
    if (self.month) {
        for (NSUInteger week = 0; week < 6; week++) {
            for (NSUInteger weekOrdial = 0; weekOrdial < 7; weekOrdial++) {
                UILabel *label = [self.dayLabels objectAtIndex:week*7 + weekOrdial];
                CalendarDay *calendarDay = [self.month.days objectAtIndex:week*7 + weekOrdial];
                
                if (calendarDay.isToday || calendarDay.isSelected) {
                    [label setTextColor:[UIColor whiteColor]];
                } else {
                    switch (weekOrdial) {
                        case 0:
                            //Sunday
                            [label setTextColor:[self getColorForProperty:DATE_SUNDAY_TEXT_COLOR]];
                            break;
                        case 6:
                            //Saturday
                            [label setTextColor:[self getColorForProperty:DATE_SATURDAY_TEXT_COLOR]];
                            break;
                        default:
                            //Weekday
                            [label setTextColor:[self getColorForProperty:DATE_WEEKDAY_TEXT_COLOR]];
                            break;
                    }
                    
                    if ([calendarDay getMonthInteger] < self.month.month ||
                        [calendarDay getMonthInteger] > self.month.month) {
                        [label setTextColor:[self getColorForProperty:DATE_PAST_TEXT_COLOR]];
                    }
                }
            }
        }
    }
}

#pragma mark Showing data to the view
- (void)updateData
{
    NSMutableArray *weekdayText = [[NSMutableArray alloc] init];
    [weekdayText addObject:NSLocalizedString(@"WEEKDAY_SUNDAY", @"Name of the weekday 0 : Sunday")];
    [weekdayText addObject:NSLocalizedString(@"WEEKDAY_MONDAY", @"Name of the weekday 1 : Monday")];
    [weekdayText addObject:NSLocalizedString(@"WEEKDAY_TUESDAY", @"Name of the weekday 2 : Tuesday")];
    [weekdayText addObject:NSLocalizedString(@"WEEKDAY_WEDNESDAY", @"Name of the weekday 3 : Wednesday")];
    [weekdayText addObject:NSLocalizedString(@"WEEKDAY_THURSDAY", @"Name of the weekday 4 : Thursday")];
    [weekdayText addObject:NSLocalizedString(@"WEEKDAY_FRIDAY", @"Name of the weekday 5 : Friday")];
    [weekdayText addObject:NSLocalizedString(@"WEEKDAY_SATURDAY", @"Name of the weekday 6 : Saturday")];
    for (NSUInteger i=0; i<7; i++) {
        [(UILabel *)[self.weekdayLabels objectAtIndex:i] setText:[weekdayText objectAtIndex:i]];
        
        for (NSUInteger j=0; j<6; j++) {
            [(UILabel *)[self.dayLabels objectAtIndex:j*7+i] setText:((CalendarDay*)[self.month.days objectAtIndex:j*7+i]).getDateString];
        }
    }
    [self updateTheme];
}

- (CGFloat)getWidthSpan
{
    return self.bounds.size.width / 7.0f;
}

- (CGFloat)getHeightSpan
{
    return (self.bounds.size.height - HEADER_IMAGE_VIEW_HEIGHT) / 6.0f;
}
@end
